package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.NcCai;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.mapper.NcCaiMapper;
import com.ruoyi.system.service.INcCaiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 蔬菜管理 服务实现
 *
 * @author ruoyi
 */
@Service
public class NcCaiServiceImpl implements INcCaiService {
    @Autowired
    private NcCaiMapper caiMapper;

    /**
     * 查询蔬菜管理数据
     *
     * @param cai 蔬菜信息
     * @return 蔬菜信息集合
     */
    @Override
    public List<NcCai> selectCaiList(NcCai cai) {
        return caiMapper.selectCaiList(cai);
    }

    @Override
    public List<NcCai> selectCaiListHasParent2(NcCai cai) {
        return caiMapper.selectCaiListHasParent2(cai);
    }

    /**
     * 查询蔬菜管理树
     *
     * @param cai 蔬菜信息
     * @return 所有蔬菜信息
     */
    @Override
    public List<Ztree> selectCaiTree(NcCai cai) {
        List<NcCai> caiList = caiMapper.selectCaiList(cai);
        List<Ztree> ztrees=new ArrayList<>();
        String parentIds=""+cai.getParams().get("caiIds");
        if(parentIds.indexOf(",") > -1){
            String[]  ids=parentIds.split(",");
            for(int i=0;i<caiList.size();i++){
                NcCai d=caiList.get(i);
                for(String id:ids){
                    if(id.equals(d.getCaiId()+"")){
                        caiList.remove(i);
                        i--;
                        continue;
                    }
                    String ance=","+d.getAncestors()+",";
                    if(ance.indexOf(","+id+",") != -1){
                        caiList.remove(i);
                        i--;
                        continue;
                    }
                }
            }
            ztrees = initZtree(caiList);
        }
        else{
            ztrees = initZtree(caiList);
        }
        return ztrees;
    }

    /**
     * 根据角色ID查询蔬菜（数据权限）
     *
     * @param role 角色对象
     * @return 蔬菜列表（数据权限）
     */
    @Override
    public List<Ztree> roleCaiTreeData(SysRole role) {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<NcCai> caiList = selectCaiList(new NcCai());
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleCaiList = caiMapper.selectRoleCaiTree(roleId);
            ztrees = initZtree(caiList, roleCaiList);
        } else {
            ztrees = initZtree(caiList);
        }
        return ztrees;
    }

    /**
     * 对象转蔬菜树
     *
     * @param caiList 蔬菜列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<NcCai> caiList) {
        return initZtree(caiList, null);
    }

    /**
     * 对象转蔬菜树
     *
     * @param caiList     蔬菜列表
     * @param roleCaiList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<NcCai> caiList, List<String> roleCaiList) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleCaiList);
        for (NcCai cai : caiList) {

            Ztree ztree = new Ztree();
            ztree.setId(cai.getCaiId());
            ztree.setpId(cai.getParentId());
            ztree.setName(cai.getCaiName());
            ztree.setTitle(cai.getCaiName());
            if (isCheck) {
                ztree.setChecked(roleCaiList.contains(cai.getCaiId() + cai.getCaiName()));
            }
            ztrees.add(ztree);

        }
        return ztrees;
    }

    /**
     * 查询蔬菜人数
     *
     * @param parentId 蔬菜ID
     * @return 结果
     */
    @Override
    public int selectCaiCount(Long parentId) {
        NcCai cai = new NcCai();
        cai.setParentId(parentId);
        return caiMapper.selectCaiCount(cai);
    }

    /**
     * 查询蔬菜是否存在用户
     *
     * @param caiId 蔬菜ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkCaiExistUser(Long caiId) {
        int result = caiMapper.checkCaiExistUser(caiId);
        return result > 0 ? true : false;
    }

    /**
     * 删除蔬菜管理信息
     *
     * @param caiId 蔬菜ID
     * @return 结果
     */
    @Override
    public int deleteCaiById(Long caiId) {
        return caiMapper.deleteCaiById(caiId);
    }

    /**
     * 新增保存蔬菜信息
     *
     * @param cai 蔬菜信息
     * @return 结果
     */
    @Override
    public int insertCai(NcCai cai) {
        NcCai info = caiMapper.selectCaiById(cai.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        /*if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new BusinessException("蔬菜停用，不允许新增");
        }*/
        cai.setAncestors(info.getAncestors() + "," + cai.getParentId());
        return caiMapper.insertCai(cai);
    }

    /**
     * 修改保存蔬菜信息
     *
     * @param cai 蔬菜信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCai(NcCai cai) {
        NcCai newParentCai = caiMapper.selectCaiById(cai.getParentId());
        NcCai oldCai = selectCaiById(cai.getCaiId());
        if (StringUtils.isNotNull(newParentCai) && StringUtils.isNotNull(oldCai)) {
            String newAncestors = newParentCai.getAncestors() + "," + newParentCai.getCaiId();
            String oldAncestors = oldCai.getAncestors();
            cai.setAncestors(newAncestors);
            updateCaiChildren(cai.getCaiId(), newAncestors, oldAncestors);
        }
        int result = caiMapper.updateCai(cai);
        /*if (UserConstants.DEPT_NORMAL.equals(cai.getStatus())) {
            // 如果该蔬菜是启用状态，则启用该蔬菜的所有上级蔬菜
            updateParentCaiStatus(cai);
        }*/
        return result;
    }

    /**
     * 修改该蔬菜的父级蔬菜状态
     *
     * @param cai 当前蔬菜
     */
    private void updateParentCaiStatus(NcCai cai) {
        String updateBy = cai.getUpdateBy();
        cai = caiMapper.selectCaiById(cai.getCaiId());
        cai.setUpdateBy(updateBy);
        caiMapper.updateCaiStatus(cai);
    }

    /**
     * 修改子元素关系
     *
     * @param caiId        被修改的蔬菜ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateCaiChildren(Long caiId, String newAncestors, String oldAncestors) {
        List<NcCai> children = caiMapper.selectChildrenCaiById(caiId);
        for (NcCai child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            caiMapper.updateCaiChildren(children);
        }
    }

    /**
     * 根据蔬菜ID查询信息
     *
     * @param caiId 蔬菜ID
     * @return 蔬菜信息
     */
    @Override
    public NcCai selectCaiById(Long caiId) {
        return caiMapper.selectCaiById(caiId);
    }

    /**
     * 校验蔬菜名称是否唯一
     *
     * @param cai 蔬菜信息
     * @return 结果
     */
    @Override
    public String checkCaiNameUnique(NcCai cai) {
        Long caiId = StringUtils.isNull(cai.getCaiId()) ? -1L : cai.getCaiId();
        NcCai info = caiMapper.checkCaiNameUnique(cai.getCaiName(), cai.getParentId());
        if (StringUtils.isNotNull(info) && info.getCaiId().longValue() != caiId.longValue()) {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

    //获取蔬菜的大类
    @Override
    public List<NcCai> selectBigClass(NcCai cai) {
        List<NcCai> list = selectCaiList(cai);
        List<NcCai> result = new ArrayList<>();
        //过滤
        for (NcCai c : list) {
            if (c.getParentId() == 0 && !"other".equals(c.getCode())) {
                //遍历取计划数量数量
                result.add(c);
            }
        }
        return result;
    }

    @Override
    public Long selectCaIdByCaiName(String caiName) {
        return caiMapper.selectCaIdByCaiName(caiName);
    }


    @Override
    public List<NcCai> selectCaiByNames(NcCai cai) {
        return caiMapper.selectCaiByNames(cai);
    }
}
